package com.itxh.core.builder;

import com.itxh.core.sqlnode.*;
import com.itxh.core.sqlsource.DynamicSqlSource;
import com.itxh.core.sqlsource.RawSqlSource;
import com.itxh.core.sqlsource.SqlSource;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.Text;

import java.util.ArrayList;
import java.util.List;

public class XMLScriptBuilder {
    private boolean isDynamic = false;

    public SqlSource parseScriptNode(Element selectElement) {
        // 获取所有的SqlNode
        SqlNode mixedSqlNode = parseDynamicTags(selectElement);
        // 在获取SqlNode的过程中，会知道是否包含${}或者是否包含动态标签
        SqlSource sqlSource = null;
        // 通过包含${}或者动态标签，来分别创建SqlSource
        if (isDynamic){
            sqlSource = new DynamicSqlSource(mixedSqlNode);
        }else{
            sqlSource = new RawSqlSource(mixedSqlNode);
        }
        return sqlSource;
    }

    private SqlNode parseDynamicTags(Element selectElement) {
        List<SqlNode> sqlNodes = new ArrayList<>();

        int nodeCount = selectElement.nodeCount();

        for (int i = 0; i < nodeCount; i++) {
            Node node = selectElement.node(i);
            if (node instanceof Text){
                String sqlText = node.getText().trim();
                if(sqlText == null || sqlText.equals("")){
                    continue;
                }
                TextSqlNode sqlNode = new TextSqlNode(sqlText);

                if (sqlNode.isDynamic()){
                    isDynamic = true;
                    sqlNodes.add(sqlNode);
                }else{
                    sqlNodes.add(new StaticTextSqlNode(sqlText));

                }
            }else if (node instanceof Element){
                isDynamic = true;

                Element element = (Element) node;
                String name = element.getName();
                if (name.equals("if")){
                    String test = element.attributeValue("test");
                    SqlNode mixedSqlNode = parseDynamicTags(element);
                    SqlNode sqlNode = new IfSqlNode(test,mixedSqlNode);
                    sqlNodes.add(sqlNode);
                }//TODO
            }else{

            }
        }

        return new MixedSqlNode(sqlNodes);
    }
}
